package com.jxzn.locust.controller.admin;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jxzn.locust.dto.ResultDTO;
import com.jxzn.locust.model.Manager;
import com.jxzn.locust.model.Role;
import com.jxzn.locust.model.SysResource;
import com.jxzn.locust.service.ManagerService;
import com.jxzn.locust.service.RoleService;
import com.jxzn.locust.service.SysResourceService;
import com.jxzn.locust.support.LoginSession;
import com.jxzn.locust.support.ResponseCode;

@Controller
@RequestMapping("")
public class LoginController {

    @Autowired
    ManagerService managerService;
    @Autowired
    RoleService roleService;
    @Autowired
    SysResourceService resourceService;

    @SuppressWarnings("unchecked")
    @PostMapping("login")
    @ResponseBody
    public ResultDTO<Object> login(HttpServletRequest request, Manager query, HttpSession session) throws UnsupportedEncodingException {

        Manager manager = managerService.findByAccount(query.getAccount());
        if (null == manager) {
            return new ResultDTO<>(ResponseCode.PARAM, "账号错误");
        }

        if (!manager.getPassword().equals(query.getPassword())) {
            return new ResultDTO<>(ResponseCode.PARAM, "密码错误");
        }
        managerService.login(manager);

        session.setAttribute(LoginSession.USER_ID.name(), manager.getId());
        session.setAttribute(LoginSession.ROLE_ID.name(), manager.getRoleId());
        session.setAttribute(LoginSession.USER_NAME.name(), manager.getName());

        Optional<Role> optional = roleService.findById(manager.getRoleId());
        if (!optional.isPresent()) {
            return ResultDTO.permission("账号异常，没有相关权限");
        }
        Role role = optional.get();
        session.setAttribute(LoginSession.SUPPER.name(), role.getMaster());
        List<SysResource> resourceList = role.getMaster() ? resourceService.findAll() : resourceService.findByRoleId(role.getId());
        String flag = "1";
        List<String> keys = new ArrayList<>(resourceList.size());
        for (SysResource sr : resourceList) {
            session.setAttribute(sr.getSessionKey(), flag);
            keys.add(sr.getSessionKey());
        }
        String permissions = StringUtils.join(keys, ",");
        permissions = URLEncoder.encode(permissions, "UTF-8");
        permissions = Base64.getEncoder().encodeToString(permissions.getBytes("UTF-8"));
        session.setAttribute("J20", permissions);
        return ResultDTO.success();
    }

    @RequestMapping("logout")
    @ResponseBody
    public String logout(HttpSession session) {
        for (LoginSession item : LoginSession.values()) {
            session.removeAttribute(item.name());
        }
        return "login";
    }

}
